import type { CLTableProps, CLTableActions } from "../types";
import { TableModel } from "./useTableModel";

const { tableLoading } = TableModel.getInstance();

/**
 * @description 使用单例模式，该类只有一个实例
 */
export const TableMethods = (function () {
  let instance: Methods | null = null;

  class Methods implements CLTableActions {
    /** 默认值 */
    #props = ref<CLTableProps>({
      tableColumn: [],
      immediate: true,
    });
    #tableData = ref<Recordable>([]);

    static getTableData = computed(() => instance!.#tableData.value);
    static getProps = computed(() => instance!.#props.value);
    static getTableColumns = computed(() => instance!.#props.value.tableColumn);

    /** 接口请求 */
    async #request() {
      try {
        console.log("request", instance!.#props.value.api);
        tableLoading.value = true;
        const { data } = await instance!.#props.value.api!();
        console.log(data, "data");

        if (!Array.isArray(data)) {
          throw new Error(
            "table组件只能接收数组数据,请检查数据类型。该数据类型为" +
              typeof data
          );
        }
        instance!.#tableData.value = data;
      } finally {
        tableLoading.value = false;
      }
    }

    /** 合并保存父组件传递的props */
    public setProps(propsData: CLTableProps) {
      Object.assign(instance!.#props.value, propsData);
      instance!.#props.value.immediate && instance!.load();
    }
    public async load() {
      console.log("load");

      instance!.#props.value.api && (await instance!.#request());
    }
  }

  return {
    getInstance: () => {
      return instance || (instance = new Methods());
    },
    Methods,
  };
})();
